package wifiunion.com.notice.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;


import java.io.File;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import wifiunion.com.notice.BaseApplication;
import wifiunion.com.notice.BaseFragment;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.ConfigureContact;
import wifiunion.com.notice.ConfigurePresenter;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.R;
import wifiunion.com.notice.UploadFileContact;
import wifiunion.com.notice.entity.HomePageConfigure;
import wifiunion.com.notice.entity.User;
import wifiunion.com.notice.presenter.AddConfigurePresenter;
import wifiunion.com.notice.presenter.UpdateNoticeConfigurePresenter;
import wifiunion.com.notice.presenter.UploadFilePresenter;
import wifiunion.com.notice.presenter.UploadImgPresenter;
import wifiunion.com.notice.utils.BitmapUtils;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.utils.UriToPathUtil;
import wifiunion.com.notice.utils.imageprocess.activity.ImageSelectorActivity;
import wifiunion.com.notice.utils.imageprocess.utils.GlideLoader;
import wifiunion.com.notice.utils.imageprocess.utils.ImageConfig;
import wifiunion.com.notice.utils.imageprocess.utils.ImageSelector;
import wifiunion.com.notice.widget.OperationDialog;

import static android.app.Activity.RESULT_OK;

/**
 * 配置首屏
 * Created by Administrator on 2016/11/23.
 */

public class CoverConfigueFragment extends BaseFragment implements View.OnClickListener, ConfigureContact.View, ConfigureContact.Callback,UploadFileContact.uploadFileView {

    private View mMainView;

    private TextView mSaveTv;

    private ImageView mIv;

    private OperationDialog mOperationDialog;
    /**
     * 相册地址 如果 值为 '-1' 代表 添加按钮
     * 首屏更新用到的列表
     */
    private ArrayList<String> mPathList = new ArrayList<String>();




    /**
     * 自定义path列表
     */
    private ArrayList<String> mSelPathList = new ArrayList<String>();

    //网络图片地址
    private String originPath = "";

    private String originSelPath = "";


    private User mUser;

    /**
     * 相册拍照请求码  添加设备过去的
     */
    public int REQUEST_CODE = 1111;


    private UploadImgPresenter mUploadPresenter;

    private ConfigureContact.Presenter mPresenter;

    private String mAuthtoken;

    private EditText mEdt;

    private AddConfigurePresenter addConfigurePresenter;

    private UpdateNoticeConfigurePresenter mUpdateNoticeConfigurePresenter;


    private View mProgressView;


    private User user;

    private RadioGroup soudRG;
    private RadioButton systemdefRB;
    private RadioButton selfRB;
    private int backgrudtype;

    private RelativeLayout mFirstSelRl;
    private RelativeLayout mFirstDefRl;

    private RelativeLayout mUploadBgRl;
    private RelativeLayout mLocationRl;
    private ImageView mNoticeBgIv;


    private RelativeLayout mViedoChooseRl;
    private LinearLayout mSelLl;
    private RadioGroup noticyTypeRG;
    private RadioButton noticeVideoRB;
    private RadioButton noitceImageRB;
    private TextView mChooseTv;
    private TextView mChooseaddTv;

    //选择的视频路径
    private String mVideoPath;
    private UploadFilePresenter mUploadFilePresenter;
    Handler handler = new Handler();
    private TextView mVideoChooseTv;

    private String originVideoPath;


    private int notificationType;

    RadioGroup.OnCheckedChangeListener soudlistener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup Group, int checkedId) {

            if (checkedId == systemdefRB.getId()) {

                backgrudtype = 0;
                showData();

            } else if (checkedId == selfRB.getId()) {
                backgrudtype = 1;
                showData();

            }


        }
    };

    RadioGroup.OnCheckedChangeListener noticyTypelistener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup Group, int checkedId) {

            if (checkedId == noticeVideoRB.getId()) {

                notificationType = 1;
                showTypeData();

            } else if (checkedId == noitceImageRB.getId()) {
                notificationType = 0;
                showTypeData();

            }


        }
    };


    public void showData()
    {
        if(backgrudtype == 0)
        {
            mFirstDefRl.setVisibility(View.VISIBLE);
            mFirstSelRl.setVisibility(View.GONE);
        }else if(backgrudtype == 1)
        {
            mFirstDefRl.setVisibility(View.GONE);
            mFirstSelRl.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_coverconfigue, container, false);
        user = SharedPreferencesUtils.getUserSharedPreferences(getContext());
        return mMainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mAuthtoken = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_AUTHTOKEN, getActivity());

        mUser = SharedPreferencesUtils.getUserSharedPreferences(getContext());

        soudRG = (RadioGroup) mMainView.findViewById(R.id.backgroud_type_rg);
        systemdefRB = (RadioButton) mMainView.findViewById(R.id.system_def);
        selfRB = (RadioButton) mMainView.findViewById(R.id.self);
        soudRG.setOnCheckedChangeListener(soudlistener);
        mFirstSelRl = (RelativeLayout) mMainView.findViewById(R.id.first_sel_rl);
        mFirstDefRl = (RelativeLayout) mMainView.findViewById(R.id.first_def_rl);

        mEdt = (EditText) mMainView.findViewById(R.id.addfirstscreen_name_edt);
        mSaveTv = (TextView) mMainView.findViewById(R.id.addfirstscreen_comfirm_tv);
        mSaveTv.setOnClickListener(this);

        mIv = (ImageView) mMainView.findViewById(R.id.addfirstscreen_iv);
        mIv.setOnClickListener(this);

        mUploadBgRl  = (RelativeLayout) mMainView.findViewById(R.id.upload_noticebg_rl);
        mUploadBgRl.setOnClickListener(this);
        mLocationRl = (RelativeLayout) mMainView.findViewById(R.id.location_rl);
        mNoticeBgIv = (ImageView) mMainView.findViewById(R.id.notice_bg_iv);


        mProgressView = mMainView.findViewById(R.id.loading_progress);



        mViedoChooseRl = (RelativeLayout) mMainView.findViewById(R.id.video_choose_rl);
        mSelLl = (LinearLayout) mMainView.findViewById(R.id.sel_img_layout);
        noticyTypeRG = (RadioGroup) mMainView.findViewById(R.id.noticytype_rg);
        noitceImageRB = (RadioButton) mMainView.findViewById(R.id.image_type_rb);
        noticeVideoRB = (RadioButton) mMainView.findViewById(R.id.video_type_rb);
        noticyTypeRG.setOnCheckedChangeListener(noticyTypelistener);

        mChooseTv = (TextView) mMainView.findViewById(R.id.notice_choose_tv);
        mChooseaddTv = (TextView) mMainView.findViewById(R.id.notice_chooseadd_tv);
        mChooseaddTv.setOnClickListener(this);

        mVideoChooseTv = (TextView) mMainView.findViewById(R.id.video_choose_tv);


        initData();

    }


    public void showTypeData()
    {
        if(notificationType == 0)
        {

            mSelLl.setVisibility(View.VISIBLE);
            mViedoChooseRl.setVisibility(View.GONE);
        }else if(notificationType == 1)
        {

            mSelLl.setVisibility(View.GONE);
            mViedoChooseRl.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.addfirstscreen_iv || i == R.id.upload_noticebg_rl) {
            showPicDialog();

        } else if (i == R.id.addfirstscreen_comfirm_tv) {

            if(backgrudtype == 0)
            {
                updateHomepage();
            }else
            {
                if(notificationType != 1)
                {
                    //走以前的流程
                    updateHomepage();
                }else if(notificationType == 1)
                {
                    uploadVideo();
                }
            }






        } else if (i == R.id.notice_chooseadd_tv) {
            Intent intent = new Intent();
            intent.setType("video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, 1005);


        }


    }


    @Override
    public void initview() {

    }

    @Override
    public void initData() {
        mPresenter = new ConfigurePresenter(getContext(), this);
        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", mAuthtoken);
        mPresenter.start(params);


    }


    /**
     * 打开相册
     */
    private void openThumb(ArrayList<String> list) {
        ImageConfig imageConfig = null;

        imageConfig = new ImageConfig.Builder(
                // GlideLoader 可用自己用的缓存库
                new GlideLoader())
                // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                .steepToolBarColor(getResources().getColor(R.color.white))
                // 标题的背景颜色 （默认黑色）
                .titleBgColor(getResources().getColor(R.color.white))
                // 提交按钮字体的颜色 （默认白色）
                .titleSubmitTextColor(getResources().getColor(R.color.backgroud_color))
                // 标题颜色 （默认白色）
                .titleTextColor(getResources().getColor(R.color.backgroud_color))
                // 开启多选 （默认为多选） (单选 为 singleSelect)
                .singleSelect()
                // 多选时的最大数量 （默认 9 张）
                .mutiSelectMaxSize(1)
                // 已选择的图片路径
                .pathList(list)/*.crop(mAspectX, mAspectY, mImageWidth, mImageHeight)*/
                .crop()
                // 拍照后存放的图片路径（默认 /temp/picture）
                .filePath(Constants.IMAGE_FILE_PATH)
                // 开启拍照功能 （默认开启）
                .requestCode(REQUEST_CODE).build();


        ImageSelector.open(this, imageConfig);

    }

    /**
     * 打开相册
     */
    private void openThumbForSel(ArrayList<String> list) {
        ImageConfig imageConfig = null;

        imageConfig = new ImageConfig.Builder(
                // GlideLoader 可用自己用的缓存库
                new GlideLoader())
                // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                .steepToolBarColor(getResources().getColor(R.color.white))
                // 标题的背景颜色 （默认黑色）
                .titleBgColor(getResources().getColor(R.color.white))
                // 提交按钮字体的颜色 （默认白色）
                .titleSubmitTextColor(getResources().getColor(R.color.backgroud_color))
                // 标题颜色 （默认白色）
                .titleTextColor(getResources().getColor(R.color.backgroud_color))
                // 开启多选 （默认为多选） (单选 为 singleSelect)
                .singleSelect()
                // 多选时的最大数量 （默认 9 张）
                .mutiSelectMaxSize(1)
                // 已选择的图片路径
                .pathList(list)/*.crop(mAspectX, mAspectY, mImageWidth, mImageHeight)*/
                // 拍照后存放的图片路径（默认 /temp/picture）
                .filePath(Constants.IMAGE_FILE_PATH)
                // 开启拍照功能 （默认开启）
                .requestCode(REQUEST_CODE).build();

        ImageSelector.open(this, imageConfig);

    }



    /**
     * 打开相机
     */
    private void openCamera(ArrayList<String> list) {
        ImageConfig imageConfig = null;
        imageConfig = new ImageConfig.Builder(
                // GlideLoader 可用自己用的缓存库
                new GlideLoader())

                // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                .steepToolBarColor(getResources().getColor(R.color.white))
                // 标题的背景颜色 （默认黑色）
                .titleBgColor(getResources().getColor(R.color.white))
                // 提交按钮字体的颜色 （默认白色）
                .titleSubmitTextColor(getResources().getColor(R.color.backgroud_color))
                // 标题颜色 （默认白色）
                .titleTextColor(getResources().getColor(R.color.backgroud_color))
                // 开启多选 （默认为多选） (单选 为 singleSelect)
                .singleSelect().pathList(list)
                // 多选时的最大数量 （默认 9 张）
                .mutiSelectMaxSize(1)/*.crop(mAspectX, mAspectY, mImageWidth, mImageHeight)*/
                .crop()
                .showCamera()
                // 直接拍照
                .directTakePicture()
                // 拍照后存放的图片路径（默认 /temp/picture）
                .filePath(Constants.IMAGE_FILE_PATH).requestCode(REQUEST_CODE).build();


        ImageSelector.open(this, imageConfig);

    }


    /**
     * 打开相机
     */
    private void openCameraForSel(ArrayList<String> list) {
        ImageConfig imageConfig = null;
        imageConfig = new ImageConfig.Builder(
                // GlideLoader 可用自己用的缓存库
                new GlideLoader())

                // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                .steepToolBarColor(getResources().getColor(R.color.white))
                // 标题的背景颜色 （默认黑色）
                .titleBgColor(getResources().getColor(R.color.white))
                // 提交按钮字体的颜色 （默认白色）
                .titleSubmitTextColor(getResources().getColor(R.color.backgroud_color))
                // 标题颜色 （默认白色）
                .titleTextColor(getResources().getColor(R.color.backgroud_color))
                // 开启多选 （默认为多选） (单选 为 singleSelect)
                .singleSelect().pathList(list)
                // 多选时的最大数量 （默认 9 张）
                .mutiSelectMaxSize(1)/*.crop(mAspectX, mAspectY, mImageWidth, mImageHeight)*/
                .showCamera()
                // 直接拍照
                .directTakePicture()
                // 拍照后存放的图片路径（默认 /temp/picture）
                .filePath(Constants.IMAGE_FILE_PATH).requestCode(REQUEST_CODE).build();


        ImageSelector.open(this, imageConfig);

    }





    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == REQUEST_CODE)
        {

            if (resultCode == RESULT_OK && data != null) {
                List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                if (pathList.contains("-1")) {
                    pathList.remove("-1");
                }

                if (requestCode == REQUEST_CODE) {
                    if (backgrudtype == 0) {
                        mPathList.clear();
                        mPathList.addAll(pathList);
                        String path = pathList.isEmpty() ? "" : pathList.get(0);


                        Glide.with(getActivity().getApplication()).load(path).placeholder(R.drawable.device_location)
                                .error(R.drawable.device_location).centerCrop().into(mIv);
                    } else if (backgrudtype == 1) {

                        mSelPathList.clear();
                        mSelPathList.addAll(pathList);
                        String path = pathList.isEmpty() ? "" : pathList.get(0);

//                    Glide.with(getActivity().getApplication()).load(path).placeholder(R.drawable.device_location)
//                            .error(R.drawable.device_location).into(mNoticeBgIv);

                        if (TextUtils.isEmpty(path)) {
                            mNoticeBgIv.setBackgroundDrawable(null);
                            mNoticeBgIv.setImageResource(0);
                            mLocationRl.setVisibility(View.VISIBLE);
                        } else {
                            Glide.with(getContext()).load(path).thumbnail((float) 0.7).into(mNoticeBgIv);
//                        Glide.with(getContext()).load(path).into(new SimpleTarget<GlideDrawable>() {
//                            @Override
//                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
//                                mNoticeBgIv.setBackgroundDrawable(resource);
//                            }
//                        });
                            mLocationRl.setVisibility(View.GONE);
                        }
                    }

                }
            }

        }else if(requestCode == 1005)
        {

            if (resultCode == RESULT_OK && data != null)
            {
                Uri uri = data.getData();
                String path = UriToPathUtil.getRealFilePath(getContext(),uri);
                if (!TextUtils.isEmpty(path)) {
                    String type = null;
                    int lastDot = path.lastIndexOf(".");
                    if (lastDot < 0) {
                        mVideoPath = "";
                        mVideoChooseTv.setText("");
                        Toast.makeText(getContext(), "目前仅支持MP4格式的视频文件", Toast.LENGTH_SHORT).show();
                    } else {
                        type = path.substring(lastDot + 1).toUpperCase();
                    }
                    if (null != type) {
                        if ("MP4".equals(type)) {
                            File file = new File(path);

                            if (file.length() > 200 * 1024 * 1024) {

                                mVideoPath = "";
                                mVideoChooseTv.setText("");
                                //文件必须必须小于200M
                                Toast.makeText(getContext(), "视频文件大小不得超过200M", Toast.LENGTH_SHORT).show();
                            }else
                            {

                                mVideoPath = path;
                                mVideoChooseTv.setText(mVideoPath);

                                //获取视频封面
//                            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
//                            retriever.setDataSource(mVideoPath);//filePath 视频文件地址
//                            Bitmap bitmap = retriever.getFrameAtTime();


                            }



                        } else {
                            Toast.makeText(getContext(), "目前仅支持MP4格式的视频文件", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }




        }

//        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 去上传
     */
    private void toUpload() {


        if(!TextUtils.isEmpty(mVideoPath))
        {
            mUploadFilePresenter = new UploadFilePresenter(getContext(), this, 0,mHandler);
            mUploadFilePresenter.uploadFile(new File(mVideoPath));
        }else
        {

        }

    }



    @Override
    public void onServerFailed(final Object errorObj) {
        mProgressView.setVisibility(View.GONE);
        Toast.makeText(getContext(), (String) errorObj, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNetFailed() {
        mProgressView.setVisibility(View.GONE);
        Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProgress() {
        mProgressView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onError(final String str) {
        try {
            mProgressView.setVisibility(View.GONE);
            Toast.makeText(getContext(), str, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onSuccess(Object obj) {

        final HomePageConfigure mpcf = (HomePageConfigure) obj;
        if (mpcf != null) {

            if(mpcf.getIsIndexConfig() == 0)
            {
                systemdefRB.setChecked(true);
                backgrudtype = 0;
                showData();

                noitceImageRB.setChecked(true);
                notificationType = 0;
                showTypeData();


            }
            if(mpcf.getIsIndexConfig() == 1)
            {
                //自定义
                selfRB.setChecked(true);
                backgrudtype = 1;
                showData();
                mLocationRl.setVisibility(View.GONE);

                noitceImageRB.setChecked(true);
                notificationType = 0;
                showTypeData();

            }
            if(mpcf.getIsIndexConfig() == 2)
            {

                selfRB.setChecked(true);
                backgrudtype = 1;
                showData();
                mLocationRl.setVisibility(View.GONE);

                noticeVideoRB.setChecked(true);
                notificationType = 1;
                showTypeData();

            }
            //上面只是判断显示哪一个，有可能两种都有值

            try {
                String result = mpcf.getIndexBanner();
                mEdt.setText(result);
                mEdt.setSelection(result.length());
            } catch (Exception e) {
                mEdt.setText("");
                e.printStackTrace();
            }
            if(!TextUtils.isEmpty(mpcf.getIndexPic()))
            {
                Glide.with(getContext()).load(Constants.HTTP_URL_IMAGESERVER + mpcf.getIndexPic()).placeholder(R.drawable.device_location)
                        .error(R.drawable.device_location).centerCrop().into(mIv);

                originPath = TextUtils.isEmpty(mpcf.getIndexPic()) ? "" : mpcf.getIndexPic();
            }


            if(mpcf.getIsIndexConfig() == 1)
            {
                if(!TextUtils.isEmpty(mpcf.getIndexBackground()))
                {
                    Glide.with(getContext()).load(Constants.HTTP_URL_IMAGESERVER + mpcf.getIndexBackground()).thumbnail((float) 0.7).into(mNoticeBgIv);

                    originSelPath = TextUtils.isEmpty(mpcf.getIndexBackground()) ? "" : mpcf.getIndexBackground();
                    mLocationRl.setVisibility(View.GONE);

                }
            }else if(mpcf.getIsIndexConfig() == 2)
            {
                originVideoPath = TextUtils.isEmpty(mpcf.getIndexBackground()) ? "" : mpcf.getIndexBackground();
                mVideoChooseTv.setText(mpcf.getIndexBackground());

                mNoticeBgIv.setBackgroundDrawable(null);
                mNoticeBgIv.setImageResource(0);
                mLocationRl.setVisibility(View.VISIBLE);
            }


        }else
        {
            systemdefRB.setChecked(true);
            backgrudtype = 0;
            showData();
        }
    }

    @Override
    public void onImgUploadSuccess(String imgpath) {
        HashMap<String, Object> params = new HashMap<>();

        addConfigurePresenter = new AddConfigurePresenter(getContext(), this, 0);

        params.put("Authorization", mAuthtoken);
        params.put("isIndexConfig", backgrudtype);
        if(backgrudtype == 0)
        {
            params.put("indexPic", imgpath);
            try {
                params.put("indexBanner", mEdt.getText().toString());
            } catch (Exception e) {
                params.put("indexBanner", "");
                e.printStackTrace();
            }

            originPath = imgpath;
            mPathList.clear();
        }
        else if(backgrudtype == 1)
        {
            params.put("indexBackground", imgpath);
            originSelPath = imgpath;
            mSelPathList.clear();
        }
        addConfigurePresenter.start(params);
    }

    @Override
    public void onAddCofigureSuccess() {


    }

    @Override
    public void onEditConfigureSuccess() {
        mProgressView.setVisibility(View.GONE);

//        BaseApplication ia = (BaseApplication) getActivity().getApplication();
//
//        ia.mHomePageConfigure.setIndexBanner(mEdt.getText().toString());
//        ia.mHomePageConfigure.setIndexPic(originPath);
        Toast.makeText(getContext(), "更新成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpdateNoticeConfigureSuccess() {

    }

    @Override
    public void onUpdateNoticeConfigureFailed(final Object obj) {
        if (obj != null) {
            Toast.makeText(getContext(), (String) obj, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onUpdatePlaceConfigureSuccess() {


    }

    @Override
    public void onUpdatePlaceConfigureFailed(final Object obj) {

    }

    @Override
    public void onUpdateStrangerConfigureSuccess() {


    }

    @Override
    public void onUpdateStrangerConfigureFailed(final Object obj) {

    }

    @Override
    public void onUpdateFZPZConfigureSuccess() {

    }

    @Override
    public void onUpdateFZPZConfigureFailed(Object obj) {

    }

    @Override
    public void getStrangerConfigueSuccess(Object obj) {

    }

    @Override
    public void getStrangerConfigueFailed(Object obj) {

    }

    @Override
    public void getDeviceListSuccess(Object obj) {

    }

    @Override
    public void getDeviceListFailed(Object obj) {

    }

    @Override
    public void updateControltimeSuccess(Object obj) {

    }

    @Override
    public void updateControltimeFailed(Object obj) {

    }


    @Override
    public void setPresenter(BasePresenter tp) {

    }

    private Handler mHandler = new Handler();


    /**
     *
     */
    private void showPicDialog() {
        mOperationDialog = new OperationDialog(getContext());
        mOperationDialog.setTitleMsg("上传照片");

        mOperationDialog.setCancelListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mOperationDialog.dismiss();
            }
        });
        mOperationDialog.setFirstOptListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(backgrudtype == 0)
                {
                    openCamera(mPathList);
                }else if(backgrudtype == 1)
                {
                    openCameraForSel(mSelPathList);
                }

                mOperationDialog.dismiss();

            }
        });
        mOperationDialog.setSecondOptListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(backgrudtype == 0)
                {
                    openThumb(mPathList);
                }else if(backgrudtype == 1)
                {
                    openThumbForSel(mSelPathList);
                }
                mOperationDialog.dismiss();

            }
        });

        mOperationDialog.show();
        mOperationDialog.setCancelable(false);
    }


    private  void uploadVideo()
    {
        onProgress();
        if(!TextUtils.isEmpty(mVideoPath))
        {
            //上传视频
            toUpload();

        }else
        {

            Log.i("text","######上传文件成功");

            HashMap<String, Object> params = new HashMap<>();

            addConfigurePresenter = new AddConfigurePresenter(getContext(), this, 0);

            params.put("Authorization", mAuthtoken);
            params.put("isIndexConfig", 2);

            params.put("indexBackground", originVideoPath);

            addConfigurePresenter.start(params);



        }


    }

    private void updateHomepage() {
        String path = "";

        if(backgrudtype == 0)
        {
            if (!mPathList.isEmpty()) {
                path = mPathList.get(0);
            }
        }else if(backgrudtype == 1)
        {
            if (!mSelPathList.isEmpty()) {
                path = mSelPathList.get(0);
            }
        }
        onProgress();

        if (TextUtils.isEmpty(path)) {
            //无修改照片，直接调用接口
            HashMap<String, Object> params = new HashMap<>();
            params.put("Authorization", mAuthtoken);
            params.put("isIndexConfig", backgrudtype);
            if(backgrudtype == 0)
            {
                params.put("indexPic", originPath);
                try {
                    params.put("indexBanner", mEdt.getText().toString());
                } catch (Exception e) {
                    params.put("indexBanner", "");
                    e.printStackTrace();
                }
            }else if(backgrudtype == 1)
            {
                params.put("indexBackground", originSelPath);
            }

            addConfigurePresenter = new AddConfigurePresenter(getContext(), this, 0);
            addConfigurePresenter.start(params);
        } else {
            //修改照片，先上传照片
            mUploadPresenter = new UploadImgPresenter(getContext(), this);
            HashMap<String, Object> params = new HashMap<>();
//            Bitmap toShowBitmap = BitmapFactory.decodeFile(path);
//            Bitmap toShowBitmap = BitmapUtils.createImageThumbnail(path);


            final String finalPath = path;
            Runnable downloadRun = new Runnable() {

                @Override
                public void run() {

                    Bitmap toShowBitmap = null;
                    try {
                        toShowBitmap = Glide.with(getContext())
                                .load(finalPath)
                                .asBitmap() //必须
                                .fitCenter()
                                .into(1280, 800)
                                .get();
                        if(null != toShowBitmap)
                        {
                            mUploadPresenter.start(toShowBitmap);
                        }
                        else
                        {
                            Toast.makeText(getContext(),"图片生成失败",0).show();
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            };

            new Thread(downloadRun).start();







//            mUploadPresenter.start(toShowBitmap);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
//        getView().setFocusableInTouchMode(true);
//        getView().requestFocus();
//        getView().setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//
//                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
//
//                    getContext().sendBroadcast(new Intent(Constants.UQUIT_APP_ACTION));
//
//                }
//                return true;
//            }
//        });
    }


    @Override
    public void onUploadFileFailed(final Object errorObj) {

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(),(String)errorObj,0).show();
                mProgressView.setVisibility(View.GONE);
            }
        },500);


    }

    @Override
    public void onUploadFileSuccess(Object data) {
        Log.i("text","######上传文件成功");
        originVideoPath = (String)data;

        HashMap<String, Object> params = new HashMap<>();
        addConfigurePresenter = new AddConfigurePresenter(getContext(), this, 0);
        params.put("Authorization", mAuthtoken);
        params.put("isIndexConfig", 2);
        params.put("indexBackground", (String)data);
        addConfigurePresenter.start(params);



    }
}
